package cn.wangxl.group.rpc.register;

import cn.wangxl.group.rpc.discover.ServiceInfo;
import cn.wangxl.group.rpc.protocol.Protocol;
import cn.wangxl.group.rpc.zookeeper.MyZkSerializer;
import com.alibaba.fastjson.JSON;
import org.I0Itec.zkclient.ZkClient;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;

/**
 * @Description ZookeeperServiceRegister
 * @Classname ZookeeperServiceRegister
 * @Created by wangxl
 * @Date 2020/9/22 22:48
 */
public class ZookeeperServiceRegister extends DefaultServiceRegister {

    private ZkClient zkClient;

    private String centerRootPath = "/simple-rpc";

    public ZookeeperServiceRegister(String zookeeperAddress) {

        zkClient = new ZkClient(zookeeperAddress);
        zkClient.setZkSerializer(new MyZkSerializer());
    }

    @Override
    public void register(ServiceObject serviceObject, Protocol protocol, int port) throws Exception{
        super.register(serviceObject, protocol, port);

        ServiceInfo serviceInfo = new ServiceInfo();

        String host = InetAddress.getLocalHost().getHostAddress();

        serviceInfo.setHost(host);

        serviceInfo.setPort(port);

        serviceInfo.setName(serviceObject.getName());

        serviceInfo.setProtocol(protocol);

        exportService(serviceInfo);
    }

    private void exportService(ServiceInfo serviceInfo){
        String serviceName = serviceInfo.getName();
        boolean exist = zkClient.exists(centerRootPath);
        if(!exist){
            zkClient.createPersistent(centerRootPath);
        }
        String servicePath = centerRootPath+"/"+serviceName;
        boolean exist1 = zkClient.exists(servicePath);
        if(!exist1){
            zkClient.createPersistent(servicePath);
        }
        String uri = JSON.toJSONString(serviceInfo);
        try {
            uri = URLEncoder.encode(uri,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        exist = zkClient.exists(servicePath+"/"+uri);
        if(exist){
            zkClient.delete(servicePath+"/"+uri);
        }
        zkClient.createEphemeral(servicePath+"/"+uri);

    }

}
